import React, { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';
import { Select, Space, Typography, Spin, Alert } from 'antd';
import type { EChartsOption } from 'echarts';
import type { SelectProps } from 'antd';
import http from '../api/http';

const { Title } = Typography;
const { Option } = Select;

interface MonthOrderData {
  monthNumber: number;
  totalAmount: number;
}

const OrderMonthChart = () => {
  // 新增年份选择状态，默认2025年
  const [selectedYear, setSelectedYear] = useState<number>(2025);
  const [orderData, setOrderData] = useState<MonthOrderData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  // 生成可选年份（当前年前后5年）
  const generateYearOptions = () => {
    const currentYear = new Date().getFullYear();
    return Array.from({ length: 11 }, (_, i) => currentYear - 5 + i);
  };

  // 补全1-12月数据（确保每个月都有数据）
  const completeMonthData = (rawData: MonthOrderData[]) => {
    // 创建1-12月的基础数据结构
    const fullMonths: MonthOrderData[] = Array.from({ length: 12 }, (_, i) => ({
      monthNumber: i + 1,
      totalAmount: 0
    }));
    
    // 用接口返回的数据覆盖基础数据
    return fullMonths.map(month => {
      const matched = rawData.find(item => item.monthNumber === month.monthNumber);
      return matched || month;
    });
  };

  // 请求订单数据（依赖选中的年份）
  useEffect(() => {
    const fetchOrderData = async () => {
      setLoading(true);
      try {
        const res = await http.get<Array<MonthOrderData>>('Order/Total', { year: selectedYear });
        // 补全月份数据后再更新状态
        const completedData = completeMonthData(res.data || []);
        setOrderData(completedData);
        setError('');
      } catch (err) {
        setError(err instanceof Error ? err.message : '数据加载失败，请重试');
        setOrderData([]);
      } finally {
        setLoading(false);
      }
    };

    fetchOrderData();
  }, [selectedYear]); // 当选中年份变化时重新请求

  // 处理年份选择变化
  const handleYearChange: SelectProps['onChange'] = (value) => {
    setSelectedYear(Number(value));
  };

  // 处理图表数据
  const processedData = {
    months: orderData.map(item => `${item.monthNumber}月`),
    amounts: orderData.map(item => item.totalAmount)
  };

  // ECharts配置项（标题随年份动态变化）
  const chartOption: EChartsOption = {
    title: {
      text: `${selectedYear}年订单月度统计`,
      left: 'center',
      textStyle: { fontSize: 16 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => `${params[0].name}：${params[0].value} 单`
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      data: processedData.months,
      axisLabel: { interval: 0 }
    },
    yAxis: {
      type: 'value',
      name: '订单数量',
      min: 0
    },
    series: [
      {
        name: '订单数',
        type: 'bar',
        data: processedData.amounts,
        barWidth: '60%',
        itemStyle: {
          color: (params: any) => params.value > 0 ? '#40a9ff' : '#f0f2f5'
        }
      }
    ]
  };

  // 渲染逻辑
  if (loading) {
    return (
      <div style={{ height: '400px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ height: '400px', padding: '20px' }}>
        <Alert
          message="加载失败"
          description={error}
          type="error"
          showIcon
        />
      </div>
    );
  }

  return (
    <div style={{ padding: '20px 0' }}>
      {/* 年份选择器 */}
      <Space style={{ marginBottom: 16 }} align="center">
        <Title level={5} style={{ margin: 0 }}>订单月度统计</Title>
        <Select
          value={selectedYear.toString()}
          style={{ width: 120 }}
          onChange={handleYearChange}
        >
          {generateYearOptions().map(year => (
            <Option key={year} value={year.toString()}>
              {year}年
            </Option>
          ))}
        </Select>
      </Space>

      {/* 图表容器 */}
      <div style={{ width: '100%', height: '400px' }}>
        <ReactECharts
          option={chartOption}
          style={{ width: '100%', height: '100%' }}
          opts={{ renderer: 'canvas' }}
        />
      </div>
    </div>
  );
};

export default OrderMonthChart;